package com.yizhiliulianta.trace;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;


import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.logging.LogRecord;

@Component
@Slf4j
public class TraceIdFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String traceId = httpServletRequest.getHeader(TraceIdConstant.TRACE_ID);

        if(StringUtils.isBlank(traceId)){
            traceId = TraceIdContext.generateTraceId();
        }

        TraceIdContext.setTraceId(traceId);
        filterChain.doFilter(servletRequest,servletResponse);
        TraceIdContext.clearTraceId();
    }
}
